class Solution
{
public:
    int minReorder(int n, vector<vector<int>> &connections)
    {
        vector<vector<int>> graph(n);
        for (auto &edge : connections)
        {
            graph[edge[0]].push_back(edge[1]);
            graph[edge[1]].push_back(-edge[0]);
        }

        int result = 0;
        queue<int> q;
        unordered_set<int> visited;
        q.push(0);
        visited.insert(0);

        while (!q.empty())
        {
            int node = q.front();
            q.pop();
            for (auto &next : graph[node])
            {
                if (visited.count(abs(next)))
                {
                    continue;
                }
                if (next > 0)
                {
                    result++;
                }
                q.push(abs(next));
                visited.insert(abs(next));
            }
        }

        return result;
    }
};